package com.example.demo;

import java.util.*;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping(value = { "/wallpapers", "/list" })
public class WallpaperController {

    @Autowired
    private WallpaperRepository wallpaperRepository;

    @ResponseBody
    @RequestMapping("")
    public PageBaseInfo list(HttpServletRequest request) {
        String title = request.getParameter("title");

        int page = 1;
        int size = 10;
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            try {
                page = Integer.parseInt(request.getParameter("page"));
            } catch (NumberFormatException e) {
            }
        }
        if (!StringUtils.isEmpty(request.getParameter("size"))) {
            try {
                size = Integer.parseInt(request.getParameter("size"));
            } catch (NumberFormatException e) {
            }
        }
        String sortby = "id";
        if (!StringUtils.isEmpty(request.getParameter("sortby"))) {
            sortby = request.getParameter("sortby");
        }
        Sort sort = Sort.by(Sort.Direction.DESC, sortby);

        if (!StringUtils.isEmpty(request.getParameter("order"))) {
            if (request.getParameter("order").equals("desc")) {
                sort = Sort.by(Sort.Direction.DESC, sortby);
            } else {
                sort = Sort.by(Sort.Direction.ASC, sortby);
            }
        }
        Specification<Wallpaper> specification = (Specification<Wallpaper>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(title)) {
                predicates.add(criteriaBuilder.like(root.get("title").as(String.class), "%" + title + "%"));
            }
            if (predicates.isEmpty()) {
                return criteriaBuilder.isNotNull(root.get("id"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        Page<Wallpaper> all = wallpaperRepository.findAll(specification, PageRequest.of(page - 1, size, sort));

        PageBaseInfo info = new PageBaseInfo(all.getContent(), page, all.getTotalElements(), size);
        return info;
    }
}